package com.lancoo.znbkxx.teacher.base

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.multidex.MultiDex
import com.devbrackets.android.exomedia.ExoMedia
import com.facebook.drawee.backends.pipeline.Fresco
import com.google.android.exoplayer2.ext.okhttp.OkHttpDataSourceFactory
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lancoo.cpbase.authentication.activities.LoginDialogActivity
import com.lancoo.cpbase.authentication.base.AddressOperater
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.cpbase.authentication.base.LoginOperate
import com.lancoo.cpbase.authentication.utils.PermissionUtils
import com.lancoo.znbkxx.teacher.BuildConfig
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.appModule
import com.lancoo.znbkxx.teacher.utils.CrashHandler
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.squareup.leakcanary.LeakCanary
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.QbSdk
import okhttp3.OkHttpClient
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import java.util.concurrent.Executors

class App : Application() {

    companion object {
        var instance: Application? = null
        fun instance() = instance ?: throw Throwable("instance 还未初始化")
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        startKoin {
            androidContext(this@App)
            modules(appModule)
        }

        MultiDex.install(this)
        QbSdk.initX5Environment(this, null)
        //        KeyboardVisibilityObserver.getInstance().init(this);
        //对单位的自定义配置, 请在 App 启动时完成
//        configUnits();
        ToastUtils.init(this) //初始化Toast控件
        Fresco.initialize(this)
        initTypeface()
        if (LeakCanary.isInAnalyzerProcess(this)) {
            //此过程专用于LeakCanary进行堆分析。在此过程中不应初始化应用程序。
            return
        }

        //加一个本地的崩溃日志，暂时还未写入过段时间进行清理
        if (XXPermissions.isGranted(this, Permission.Group.STORAGE)) {
            if (BuildConfig.DEBUG) {
                CrashHandler.getInstance().init(this)
            }
        }
        // mmkv
        MMKV.initialize(this)
        //        LeakCanary.install(this);//内存泄漏检测工具
        initBugly()
        registerLifecycle()
        configureExoMedia(this)
    }

    private fun initBugly() {
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog
        Bugly.init(applicationContext, "bed26d8dbe", false)
    }

    private fun initTypeface() {
        val myTypeface = Typeface.createFromAsset(assets, "fonts/Arial.ttf")
        try {
            val field = Typeface::class.java.getDeclaredField("MONOSPACE")
            field.isAccessible = true
            field[null] = myTypeface
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }

    /*
     * 优化了重登录，你把上面的代码放到Application类中，
     * 然后再oncreate方法中掉用一下，当用户从后台切换到前台，或者将应用杀死再进入，
     * 假如token失效了，会通过保存到本地的账号和密码进行自动重登录。
     * */
    private var count = 0
    private fun registerLifecycle() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityStopped(activity: Activity) {
                Log.v("viclee", activity.toString() + "onActivityStopped")
                count--
                if (count == 0) {
                    Log.v("viclee", ">>>>>>>>>>>>>>>>>>>切到后台  lifecycle")
                    (activity as? LoginDialogActivity)?.finish()
                }
            }

            @SuppressLint("CheckResult")
            override fun onActivityStarted(activity: Activity) {
                if (PermissionUtils.checkPermission(applicationContext,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                        && PermissionUtils.checkPermission(applicationContext,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Log.v("viclee", activity.toString() + "onActivityStarted")
                    if (count == 0) {
                        Log.v("viclee", ">>>>>>>>>>>>>>>>>>>切到前台  lifecycle")
                        //重登录
                        try {
                            val addressOperater = AddressOperater(applicationContext)
                            val baseAdress = addressOperater.baseAddress
                            if (!TextUtils.isEmpty(baseAdress)) {
                                val singleThreadExecutor = Executors.newSingleThreadExecutor()
                                singleThreadExecutor.execute {
                                    val operate = LoginOperate(applicationContext)
                                    if (!TextUtils.isEmpty(CurrentUser.Token)) {
                                        //0 无效； 1 有效；-1 没网；-2 超时
                                        val state = operate.tokenCheck(baseAdress)
                                        Log.i("TAG", "application state:$state")
                                        if (state != 1) {
                                            operate.reLoginReWrite()
                                        }
                                    } else {
                                        operate.reLoginReWrite()
                                    }
                                }
                            }
                        } catch (e: Exception) {
                        }
                    }
                    count++
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
                Log.v("viclee", activity.toString() + "onActivitySaveInstanceState")
            }

            override fun onActivityResumed(activity: Activity) {
                Log.v("viclee", activity.toString() + "onActivityResumed")
            }

            override fun onActivityPaused(activity: Activity) {
                Log.v("viclee", activity.toString() + "onActivityPaused")
            }

            override fun onActivityDestroyed(activity: Activity) {
                Log.v("viclee", activity.toString() + "onActivityDestroyed")
            }

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                Log.v("viclee", activity.toString() + "onActivityCreated")
            }
        })
    }

    private fun configureExoMedia(application: Application) {
        ExoMedia.setDataSourceFactoryProvider { userAgent, listener ->
            val okHttpDataSourceFactory = OkHttpDataSourceFactory(OkHttpClient(), userAgent, listener)
            //                SimpleCache cache = new SimpleCache(new File(getCacheDir(), "ExoMediaCache"),new NoOpCacheEvictor());
//                SimpleCache cache = new SimpleCache(new File(getCacheDir(), "ExoMediaCache"),new LeastRecentlyUsedCacheEvictor((5)));
            CacheDataSourceFactory(VideoCache.getInstance(application.baseContext), okHttpDataSourceFactory)
        }
    }

}